<template>
  <!-- 首页 地图 -->
  <div
    class="index-map-asdfjalskdjfkslajfklashdfjhasdjklfljasklf"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <!-- 高德地图 -->
    <div id="container" class="width-height-100"></div>
  </div>
</template>
  
<script>
import * as api from "./api";
import util from "@/libs/util";
import mapPop from "./mappop";
import Vue from "vue";
import flvjs from "@/views/common/flv-video";

export default {
  name: "video-management-new-index-map",
  components: {
    // mapPop
  },
  props: ["list"],
  data() {
    return {
      map: null, // 地图
      loading: false,
      imVideo: null,
      polygon: null,
      camId: null,
      playId: null,
      cluster: null, // 点聚合
      flvPlayer: null,
      orNot: true,
    };
  },
  created() {
    this.initMap();
  },
  mounted() {
  },
  computed: {
    // 监听选中摄像机变化
    listenCameraChangeState() {
      return this.$store.state.user.cameraChange;
    },
  },

  watch: {
    list: {
      handler(val, oldval) {
        if (val) {
          console.log(val);
          // this.initMap()
          // this.initCity('山东省')
          // this.addPoint(val, 1)
        }
      },
      // immediate: true,
      deep: true,
    },

    /**
     * 选中摄像机变化
     */
    listenCameraChangeState: function (val, old) {
      console.log("监听到变化啦.....");
      // 根据class获取到当前弹窗
      var cc = document.getElementsByClassName("camera-choose");
      if (
        cc == null ||
        cc == undefined ||
        cc[0] == null ||
        cc[0] == undefined
      ) {
        return;
      }
      this.closeVideo();
      this.camId = val["camId"];

      api
        .getVideo({
          camId: val["camId"],
          type: 1,
        })
        .then((res) => {
          this.imVideo = res;

          if (this.imVideo != null && this.imVideo != undefined) {
            this.playId = this.imVideo["data"]["playId"];
          }

          // 重新绑定
          var params = {
            data: val,
            url:
              this.imVideo != null && this.imVideo != undefined
                ? this.imVideo["data"]["liveUrl"]
                : "",
            pic: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.ntimg.cn%2F20140315%2F10185900_164537024352_2.jpg&refer=http%3A%2F%2Fpic.ntimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1656664716&t=4e8155e7ff5aaa1b0843f9dacb909869",
          };

          var div = document.createElement("div");
          div.className = "camera-choose";

          var Profile = Vue.extend(mapPop);

          var instance = new Profile({
            propsData: {
              sourceData: params,
              xclose: (e) => {
                console.log("player.......");
                console.log(e);
                this.flvPlayer = e.flvPlayer;
              },
            },
          }).$mount();

          cc[0].append(instance.$el);
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },


  methods: {
    /** 查询部门下拉树结构 */
    // getCameraTreeselect() {
    //   api.treeCameraData().then((response) => {
    //     console.log(response);
    //     console.log(response.data[0]);
    //     this.current = response.data[0].id;
    //     this.getCameraList();
    //   });
    // },
    // getCameraList() {
    //   if (this.current && this.current !== null && this.current !== undefined) {
    //     console.log(this.current);
    //     api
    //       .getCamerasIndex({ deptId: this.current })
    //       .then((res) => {
    //         console.log(res);
    //         var responce = JSON.parse(JSON.stringify(res));
    //         responce["list"] = res.data;
    //         console.log(responce);
    //         this.$nextTick(() => {
    //           this.clickTree(responce);
    //         });

    //         console.log(2222222);
    //         if (responce.camId == null) {
    //           this.$refs.mapView.clusterReady(responce);
    //         }
    //       })
    //       .catch((err) => {
    //         console.log(err);
    //       });
    //   }
    // },
    // 初始化地图
    initMap() {
      console.log(99999999);
      var that = this;
      var opts = {
        subdistrict: 0,
        extensions: "all",
        level: "province",
      };
      //利用行政区查询获取边界构建mask路径
      //也可以直接通过经纬度构建mask路径
      var district = new AMap.DistrictSearch(opts);
      district.search("山东省", function (status, result) {
        var bounds = result.districtList[0].boundaries;
        var mask = [];
        for (var i = 0; i < bounds.length; i += 1) {
          mask.push([bounds[i]]);
        }
        that.map = new AMap.Map("container", {
          mask: mask,
          resizeEnable: true,
          expandZoomRange: true,
          dragEnable: true,
          mapStyle: "amap://styles/light", //样式
          zoom: 8,
          zooms: [4, 19],
          center: [118.381501, 36.171985],
          pitch: 30, // 俯仰角度，默认0，[0,83]，2D地图下无效 。（自V1.4.0开始支持）
          viewMode: "3D",
          showLabel: true,
          labelzIndex: 10, // 多边形覆盖物的叠加顺序。地图上存在多个多边形覆盖物叠加时，通过该属性使级别较高的多边形覆盖物在上层显示.
          zoomEnable: true,
        });
        //添加描边
        for (var i = 0; i < bounds.length; i += 1) {
          new AMap.Polyline({
            path: bounds[i],
            strokeColor: "#a3ccff",
            strokeWeight: 4,
            map: that.map,
          });
        }
        that.map.on("click", function (e) {
          that.map.clearInfoWindow();
        });
      });
    },
    // initMap() {
    //   // 创建地图
    //   this.map = new AMap.Map("container", {
    //     resizeEnable: true,
    //     expandZoomRange: true,
    //     dragEnable: true,
    //     zoom: 7.5,
    //     zooms: [4, 19],
    //     center: [118.381501, 36.171985],
    //     pitch: 30, // 俯仰角度，默认0，[0,83]，2D地图下无效 。（自V1.4.0开始支持）
    //     viewMode: '3D',
    //     showLabel: true,
    //     labelzIndex: 10, // 多边形覆盖物的叠加顺序。地图上存在多个多边形覆盖物叠加时，通过该属性使级别较高的多边形覆盖物在上层显示.
    //     zoomEnable: true,
    //   });

    //   this.initCity('山东省')
    // },

    // 区域遮盖
    // initCity(city) {
    //   var _this = this
    //   if (_this.polygon) {
    //     _this.map.remove(_this.polygon)
    //   }
    //   AMap.plugin('AMap.DistrictSearch', function () {
    //     new AMap.DistrictSearch({
    //       extensions: 'all',
    //       subdistrict: 0
    //     }).search(city, function (status, result) {// 外多边形坐标数组和内多边形坐标数组
    //       var outer = [
    //         new AMap.LngLat(-360, 90, true),
    //         new AMap.LngLat(-360, -90, true),
    //         new AMap.LngLat(360, -90, true),
    //         new AMap.LngLat(360, 90, true)
    //       ]
    //       var holes = result.districtList[0].boundaries
    //       var pathArray = [outer]
    //       pathArray.push.apply(pathArray, holes)
    //       _this.polygon = new AMap.Polygon({
    //         pathL: pathArray,
    //         strokeColor: '#99ffff',//城市边界颜色
    //         strokeWeight: 3,
    //         fillColor: '#a3ccff', // 遮罩背景色黑色
    //         fillOpacity: 0.5
    //       })
    //       _this.polygon.setPath(pathArray)
    //       _this.map.add(_this.polygon)

    //       _this.map.on('click', function (e) {
    //         _this.closeVideo()
    //         _this.map.clearInfoWindow()
    //       })
    //     })
    //   })
    // },

    //  刷新相机数据 单个相机
    refreshCamera(val) {
      // console.log(val, '单个相机')

      this.removePoint();
      this.addPoint([val], 0);
      this.closeVideo();
      if (this.cluster != null) {
        this.cluster.setMap(null);
      }
      var cc = document.getElementsByClassName("camera-choose");
      console.log(cc);
      if (
        cc != null &&
        cc != undefined &&
        cc[0] != null &&
        cc[0] != undefined &&
        cc[0].childNodes.length > 0
      ) {
        // 弹窗打开了 切换弹窗内容
        this.$store.state.user.cameraChange = val;
      } else {
        this.removePoint();
        this.addPoint([val], 0);
        this.closeVideo();
      }
    },

    // 点聚合 点击单个相机时触发
    async clusterReady(val) {
      console.log(val, "kkk");
      var list = val.list;

      if (!util.listNotEmpty(list)) {
        this.$modal.msgSuccess("当前机构无相机！");
        return;
      }

      // 不再查询数据 直接展示val.children
      this.removePoint();

      var res = [];
      for (let i = 0; i < list.length; i++) {
        var cc = {};

        // 判定经纬度是否正常
        if (
          !(
            util.isNotEmpty(list[i]["camLong"]) &&
            util.isNotEmpty(list[i]["camLat"])
          )
        ) {
          continue;
        }

        // 经纬度
        cc["lnglat"] = [list[i]["camLong"], list[i]["camLat"]];

        // 相机数据
        cc["camData"] = list[i];

        res.push(cc);
      }

      this.orNot = false; // map不打点
      this.addPoint(list, 1);
    },
    //  地图图标
    chooseIcon(val) {
      if (val["status"] == 0) {
        return require("@/assets/images/cameraok.png");
      } else {
        return require("@/assets/images/cameranook.png");
      }
    },

    // 点标记
    addPoint(points, type) {
      console.log(points);
      var _this = this;
      _this.loading = true;
      var markerList = [];
      if (util.listNotEmpty(points)) {
        for (let i = 0; i < points.length; i++) {
          // marker改为LabelMarker 性能更好
          var icon = {
            // 图标类型，现阶段只支持 image 类型
            type: "image",
            // 图片 url
            image: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            // 图片尺寸
            // size: [64, 30],
            // 图片相对 position 的锚点，默认为 bottom-center
            anchor: "center",
          };

          var text = {
            // 要展示的文字内容
            content: points[i]["camName"],
            // 文字方向，有 icon 时为围绕文字的方向，没有 icon 时，则为相对 position 的位置
            direction: "right",
            // 在 direction 基础上的偏移量
            offset: [-20, -5],
            // 文字样式
          };

          // 点标记 marker
          var marker = new AMap.Marker({
            lnglat: new AMap.LngLat(points[i]["camLong"], points[i]["camLat"]),

            icon: new AMap.Icon({
              // 图标尺寸
              size: new AMap.Size(32, 32),
              // 图标的取图地址
              image: _this.chooseIcon(points[i]),
              // 图标所用图片大小
              // imageSize: new AMap.Size(135, 40),
              // 图标取图偏移量
              // imageOffset: new AMap.Pixel(-9, -3)
            }),
            position: new AMap.LngLat(
              points[i]["camLong"],
              points[i]["camLat"]
            ),
            extData: points[i], // 相机数据
          });

          marker.on("mouseover", function (e) {
            marker.setTop(true);
          });

          marker.on("mouseout", function (e) {
            marker.setTop(false);
          });

          marker.setTitle(points[i]["camName"]);

          // 绑定弹窗页面
          var infoWindow = new AMap.InfoWindow({
            anchor: "bottom-center",
            isCustom: true,
            offset: new AMap.Pixel(10, -32),
          });

          // 点击图标
          var onMarkerClick = function (e) {
            _this.closeVideo();
            // console.log('点击地图图标：')
            var camData = e.target.getExtData();
            this.camId = camData["camId"];

            // _this.loading = true
            api
              .getVideo({
                camId: camData["camId"],
                type: 1,
              })
              .then((res) => {
                _this.loading = false;
                _this.imVideo = res;

                if (_this.imVideo != null && _this.imVideo != undefined) {
                  _this.playId = _this.imVideo["data"]["playId"];
                }

                infoWindow.setContent(_this.getContent(camData));
                infoWindow.open(_this.map, e.target.getPosition()); // 打开信息窗体 e.target就是被点击的Marker
              })
              .catch((err) => {
                console.log(err);
                infoWindow.setContent(_this.getContent(camData));
                infoWindow.open(_this.map, e.target.getPosition());
                _this.loading = false;
              });
          };

          // 地图缩放
          // _this.map.on('zoomend', function () {
          //   var zoom = _this.map.getZoom();
          //   // 关闭信息弹窗
          //   _this.closeVideo()
          //   _this.map.clearInfoWindow();
          // });

          marker.on("click", onMarkerClick); // 绑定click事件
          // 打点
          if (type == 0) {
            // 中心点变化
            this.map.setCenter([points[i]["camLong"], points[i]["camLat"]]);
            this.map.add(marker);
          }

          markerList.push(marker);

          if (i == points.length - 1) {
            _this.loading = false;
          }
        }

        // 点聚合 1.4.15
        if (markerList != null && markerList.length > 0 && type == 1) {
          this.pointsCluster(markerList);
        }
      } else {
        _this.loading = false;
      }
    },
    // 点聚合
    pointsCluster(markers) {
      var sts = [
        {
          url: "https://webapi.amap.com/theme/v1.3/m1.png",
          size: new AMap.Size(53, 53),
          lineHeight: 53,
          offset: new AMap.Pixel(-26.5, -26.5),
        },
        {
          url: "https://webapi.amap.com/theme/v1.3/m2.png",
          size: new AMap.Size(56, 56),
          lineHeight: 56,
          offset: new AMap.Pixel(-28, -28),
        },
        {
          url: "../images/camera/map_cluster_m3.png",
          size: new AMap.Size(66, 66),
          lineHeight: 66,
          offset: new AMap.Pixel(-33, -33),
        },
      ];
      var _this = this;
      var cluster;
      var count = markers.length;
      var _renderClusterMarker = function (context) {
        var factor = Math.pow(context.count / count, 1 / 18);
        var div = document.createElement("div");
        var Hue = 180 - factor * 180;
        var bgColor = "hsla(" + Hue + ",100%,40%,0.7)";
        var fontColor = "hsla(" + Hue + ",100%,90%,1)";
        var borderColor = "hsla(" + Hue + ",100%,40%,1)";
        var shadowColor = "hsla(" + Hue + ",100%,90%,1)";
        div.style.backgroundColor = bgColor;
        var size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
        div.style.width = div.style.height = size + "px";
        div.style.border = "solid 1px " + borderColor;
        div.style.borderRadius = size / 2 + "px";
        div.style.boxShadow = "0 0 5px " + shadowColor;
        div.innerHTML = context.count;
        div.style.lineHeight = size + "px";
        div.style.color = fontColor;
        div.style.fontSize = "14px";
        div.style.textAlign = "center";

        context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
        context.marker.setContent(div);
      };

      if (_this.cluster) {
        // 移除聚合点
        _this.cluster.setMap(null);
      }

      // 加载点聚合插件
      this.$nextTick(() => {
        cluster = new AMap.MarkerClusterer(_this.map, markers, {
          gridSize: 60,
          renderClusterMarker: _renderClusterMarker,
        });
        _this.cluster = cluster;
        if (_this.deptId == null || _this.deptId === "") {
          _this.map.setCenter([118.381501, 36.171985]);
        }
        _this.orNot = true;
        var overlays = _this.map.getAllOverlays("marker");
        _this.map.setZoom(8);
        _this.map.setFitView(overlays); // map自适应
      });
    },

    // map移除点标记
    removePoint() {
      this.map.clearMap();
      this.closeInfoWindow();

      if (this.cluster != null) {
        this.cluster.setMap(null);
      }
    },

    /** 地图弹窗 */
    getContent(data) {
      var params = {
        data: data,
        url: this.imVideo != null ? this.imVideo["data"]["liveUrl"] : "",
        eventType: data.eventType, // 事件
        pic: this.getUUrl(data),
      };
      var div = document.createElement("div");
      div.className = "camera-choose";

      var Profile = Vue.extend(mapPop);
      var instance = new Profile({
        propsData: {
          sourceData: params,
          xclose: (e) => {
            this.flvPlayer = e.flvPlayer;
          },
        },
      }).$mount();
      div.append(instance.$el);
      return div;
    },

    /**
     * 获取图片url
     */
    getUUrl(data) {
      if (data != null) {
        if (util.isNotEmpty(data["eventUrl"])) {
          return data["eventUrl"];
        } else if (util.isNotEmpty(data["imgUrl"])) {
          return data["imgUrl"];
        }
      }
    },

    // 关闭视频流
    closeVideo() {
      var cc = document.getElementsByClassName("camera-choose");
      // if (this.camId != null && this.playId != null) {
      //   var param = {
      //     camId: this.camId,
      //     playId: this.playId
      //   }
      //   console.log(param)
      //   api.closeVideo(param).then(res => {
      //     console.log(res)
      //   }).catch(err => {
      //     // console.log(err)
      //   })
      // }
      if (
        cc != null &&
        cc != undefined &&
        cc[0] != null &&
        cc[0] != undefined &&
        cc[0].childNodes.length > 0
      ) {
        cc[0].removeChild(cc[0].childNodes[0]);
        if (this.flvPlayer != null && this.flvPlayer.e) {
          flvjs.stopPlayer(this.flvPlayer);
        }
      }
      if (this.flvPlayer != null && this.flvPlayer.e) {
        flvjs.stopPlayer(this.flvPlayer);
      }
    },
    //关闭信息窗体
    closeInfoWindow() {
      this.map.clearInfoWindow();
    },
  },
};
</script>
  
<style scoped lang="scss"></style>
  
<style lang="scss">
.index-map-asdfjalskdjfkslajfklashdfjhasdjklfljasklf {
  position: absolute;
  width: 100%;
  height: calc(100% - 50px);

  .camera-choose {
    z-index: 250 !important;
    border: 1px solid black;
    // overflow:hidden!important;
  }

  .width-height-100 {
    width: 100%;
    height: 100%;
  }
}
</style>